<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form :inline="true" class="demo-form-inline" label-position="left" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="search.acName" placeholder="请输入用户名" clearable />
                </el-form-item>
                <el-form-item label="用户账号">
                    <el-input v-model="search.userName" placeholder="请输入用户账号" clearable />
                </el-form-item>
                <el-form-item label="用户归属" prop="cityName">
                    <el-select v-model="search.cityName" filterable placeholder="请输入用户归属" remote
                        :remote-method="remoteMethodOrg" :loading="userLoading">
                        <el-option v-for="item in orgList" :key="item.cityName" :label="item.cityName"
                            :value="item.cityName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-button type="primary" @click="handleaddAccountInfo">新增</el-button>
        </div>
        <el-table :data="rolesList" style="width: 100%;margin-top:16px;" border class="table-box" v-loading="loading"
            :height="height + 'px'">
            <el-table-column align="center" label="序号" width="80">
                <template slot-scope="scope">
                    {{ (pagination.pageNum - 1) * pagination.pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="用户名" v-element-table-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.acName }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="用户账号" v-element-table-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.userName }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="用户归属" v-element-table-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.cityName }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="联系电话" v-element-table-tooltip>
                <template slot-scope="scope">
                    {{ scope.row.phone }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="170">
                <template slot-scope="scope">
                    <el-button type="text" @click="handleEdit(scope)">编辑</el-button>
                    <el-button type="text" @click="changePassword(scope)">重置密码</el-button>
                    <el-button type="text" @click="handleDelete(scope)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize"
            @pagination="getPagination" />
        <el-dialog :visible.sync="dialogVisible"
            :title="dialogType === 'changePassword' ? '重置密码' : dialogType === 'edit' ? '编辑' : '新增'"
            :close-on-click-modal="false">
            <el-form :model="role" label-width="80px" label-position="right" :rules="rules" ref="ruleForm">
                <el-row :gutter="20">
                    <el-col :span="24" v-if="dialogType !== 'changePassword'">
                        <el-form-item label="用户名" prop="acName">
                            <el-input v-model="role.acName" placeholder="请输入用户名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="用户账号" prop="userName">
                            <el-input v-model="role.userName" placeholder="请输入用户账号"
                                :disabled="dialogType == 'edit' || dialogType == 'changePassword'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="dialogType != 'edit'">
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="role.password" placeholder="请输入密码" show-password />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="dialogType !== 'changePassword'">
                        <el-form-item label="用户归属" prop="cityName">
                            <el-select v-model="role.cityName" filterable placeholder="请输入用户归属" remote
                                :remote-method="remoteMethodOrg" :loading="userLoading">
                                <el-option v-for="item in orgList" :key="item.cityName" :label="item.cityName"
                                    :value="item.cityName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="dialogType !== 'changePassword'">
                        <el-form-item label="联系电话" prop="phone">
                            <el-input v-model="role.phone" placeholder="请输入联系电话" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div style="text-align:right;">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRole">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { selectAcNameAndUserName, addAccountInfo, deleteAccountInfo, updateAccountInfo, getOrg } from '@/api/api'
import Pagination from '@/components/Pagination'
import addDialog from './components/addDialog.vue'
import MD5 from 'MD5'
const defaultRole = {}
export default {
    name: 'work',
    components: { Pagination, addDialog },
    data() {
        let validatePass = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入密码'));
            } else if (value.length < 6) {
                callback(new Error('密码最少6位'));
            } else if (value.length > 20) {
                callback(new Error('新密码不能超过20位'));
            } else {
                callback();
            }
        };
        return {
            typeList: projectType,
            rules: {
                cityName: [
                    { required: true, message: '请输入用户归属', trigger: 'change' }
                ],
                password: [
                    { required: true, validator: validatePass, trigger: 'change' }
                ],
                acName: [
                    { required: true, message: '请输入用户名', trigger: 'change' }
                ],
                userName: [
                    { required: true, message: '请输入用用户账号', trigger: 'change' }
                ],
            },
            loading: false,
            userLoading: false,
            height: 400,
            total: 0,
            role: Object.assign({}, defaultRole),
            routes: [],
            rolesList: [],
            dialogVisible: false,
            dialogType: 'new',
            defaultProps: {
                children: 'children',
                label: 'title'
            },
            search: {},
            pfOptions: [],
            zxOptions: [],
            pagination: {
                'pageNum': 1,
                'pageSize': 20
            },
            time: null,
            orgList: [],
        }
    },
    watch: {
        dialogVisible(val) {
            if (!val) {
                this.role = {}
                this.$refs['ruleForm'].resetFields();
                this.orgList = []
            }
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            if (to.path == '/work/list') {
                vm.onSubmit();
            }
        });
    },
    computed: {
        routesData() {
            return this.routes
        }
    },
    created() {
        this.getTasks();
        this.height = this.getHeight();
        let that = this;
        window.onresize = function (event) {
            that.height = that.getHeight();
        };
    },
    methods: {
        gerOrgList(cityName) {
            this.userLoading = false;
            getOrg({ cityName }).then(res => {
                this.orgList = res || []
            })
        },
        remoteMethodOrg(query) {
            if (query !== '') {
                this.userLoading = true;
                this.gerOrgList(query.toLowerCase())
            } else {
                this.orgList = [];
            }
        },
        getHeight() {
            let winHieght = window.innerHeight;
            return winHieght - 280;
        },
        onSubmit() {
            this.pagination = {
                "pageNum": 1,
                "pageSize": 20
            }
            this.getTasks()
        },
        reset() {
            this.search = {}
            this.onSubmit()
        },
        getPagination(pagination) {
            this.pagination = pagination
            this.getTasks()
        },
        getColor(finishState) {
            const colors = {
                '超前': '#1ecd00',
                '正常': '#1ecd00',
                '已完成': '#1ecd00',
                '进行中': '#1890ff',
                '待开始': '#999',
                '已延期': '#ff4949',
                '落后': '#ff4949'
            }
            return colors[finishState]
        },
        truncateToFixed(value, decimals) {
            const integerPart = Math.trunc(value || 0); // 获取整数部分
            const decimalPart = value - integerPart; // 获取小数部分
            const factor = Math.pow(10, decimals);
            const truncatedDecimalPart = decimalPart < 0 ? Math.ceil(decimalPart * factor) / factor : Math.floor(decimalPart * factor) / factor; // 根据正负选择向上或向下截断
            return integerPart + truncatedDecimalPart; // 组合整数部分和小数部分
        },
        goDetail(scope) {
            this.$message({
                type: 'warning',
                message: '详情功能建设中…'
            })
            // this.$router.push({
            //     path: `/sweeklyReport/ganttDetail/${scope.row.keyId}`
            // })
        },
        async getTasks() {
            try {
                this.loading = true
                const res = await selectAcNameAndUserName({ page: this.pagination.pageNum, size: this.pagination.pageSize, ...this.search });
                this.total = res.total || 0;
                this.rolesList = res?.list || [];
                this.loading = false
            } catch (error) {
                this.loading = false
            }
        },
        handleaddAccountInfo() {
            this.orgList = []
            this.role = Object.assign({}, defaultRole)
            this.dialogType = 'new'
            this.dialogVisible = true
        },
        async handleEdit(scope) {
            await this.getEdit(scope)
        },
        getEdit(scope) {
            this.dialogType = 'edit'
            this.dialogVisible = true
            this.role = { ...scope.row }
        },
        changePassword(scope) {
            this.dialogType = 'changePassword'
            this.dialogVisible = true
            this.role = { ...scope.row, password: '' }
            this.$refs['ruleForm'] && this.$refs['ruleForm'].resetFields();
        },
        handleDelete({ $index, row }) {
            this.$confirm(`确认删除“${row.userName}”的用户账号?`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    deleteAccountInfo(row.userId).then(res => {
                        if (res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            })
                            this.getTasks();
                        } else {
                            this.$message({
                                type: 'warning',
                                message: res.message
                            })
                            this.getTasks();
                        }
                    })
                })
                .catch(err => { console.error(err) })
        },
        confirmRole() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    const isEdit = this.dialogType === 'edit'
                    const isPwd = this.dialogType === 'changePassword'
                    if (isPwd) {
                        updateAccountInfo({ ...this.role, password: MD5(this.role.password) }).then(res => {
                            this.dialogVisible = false
                            this.getTasks()
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            })
                        })
                    } else if (isEdit) {
                        updateAccountInfo({ ...this.role }).then(res => {
                            this.dialogVisible = false
                            this.getTasks()
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            })
                        })
                    } else {
                        addAccountInfo({ ...this.role, password: MD5(this.role.password) }).then(res => {
                            this.dialogVisible = false
                            this.getTasks()
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            })
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    overflow-y: auto;
    height: calc(100vh - 86px);
    padding: 16px 20px 0;

    .roles-table {
        margin-top: 30px;
    }

    .permission-tree {
        margin-bottom: 30px;
    }
}


.filter-container {
    ::v-deep .el-form-item {
        margin-bottom: 0;
    }
}

::v-deep .el-select,
::v-deep .el-date-editor.el-input,
::v-deep .el-date-editor.el-input__inner {
    width: 100%;
}

.table-box {
    ::v-deep .el-button--medium {
        padding: 0px 5px;
    }
}

.popover-list {
    min-height: 30px;
    line-height: 30px;
    cursor: pointer;
    padding: 0 10px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;

    &:hover {
        background: #f3f6fb;
    }
}

.all-num-box {
    margin-left: 20px;

    .green {
        color: #1ecd00;
        margin: 0 2px;
    }

    .blue {
        color: #1890ff;
        margin: 0 2px;
    }
}

::v-deep .el-date-editor--daterange.el-input__inner {
    width: 240px;
}

::v-deep .table-box .el-button--medium {
    padding: 0;
}

::v-deep .el-input-number--medium {
    width: 100%;
}

::v-deep .el-input-number.is-controls-right .el-input__inner {
    text-align: left;
}
</style>
<style>
.popper-list {
    padding: 0;
}

.popperClass {
    width: 500px;
}
</style>